<template>
  <div class="inspectionSheet">
    <div class="mian">
      <el-descriptions title="质量检验表" :column="6" border>
        <el-descriptions-item :span="6" label="检验阶段">
          <div>
            <el-radio-group v-model="ruleForm.checkStage" @change="handleChangeCheck">
              <el-radio v-for="item, index in radioList" :key="index" :label="item">{{ item.checkStageName
                }}</el-radio>
            </el-radio-group>
          </div>
          <span class="message">{{ validateMsg.checkStage }}</span>
        </el-descriptions-item>
        <el-descriptions-item :span="2" label="供应商">
          <el-input v-model="ruleForm.supplier" placeholder="请输入供应商名称"></el-input>
          <span class="message">{{ validateMsg.supplier }}</span>
        </el-descriptions-item>
        <el-descriptions-item :span="2" label="检验时间">
          <el-date-picker class="w100p" v-model="ruleForm.checkTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择检验时间">
          </el-date-picker>
          <span class="message">{{ validateMsg.checkTime }}</span>
        </el-descriptions-item>
        <el-descriptions-item :span="2" label="码单号">
          <el-input v-model="ruleForm.codeNo" placeholder="请输入码单号"></el-input>
          <span class="message">{{ validateMsg.codeNo }}</span>
        </el-descriptions-item>
        <el-descriptions-item :span="2" label="投入设施">
          <el-select class="w100p" v-model="ruleForm.facilityId" clearable filterable placeholder="请选择设施名称"
            @change="getFacilityName">
            <el-option v-for="(item, index) in facilityList" :key="index" :label="item.facilityName"
              :value="item.facilityId" />
          </el-select>
          <span class="message">{{ validateMsg.facilityId }}</span>
        </el-descriptions-item>

        <el-descriptions-item :span="2" label="检验品种">
          <el-select v-model="ruleForm.plantVarietyId" class="w100p" placeholder="请选择品种" @change="getPlantVarietyName">
            <el-option v-for="item, index in varietyList" :key="index" :label="item.plantVarietyName"
              :value="item.plantVarietyId"></el-option>
          </el-select>
          <span class="message">{{ validateMsg.plantVarietyId }}</span>
        </el-descriptions-item>
        <el-descriptions-item :span="2" label="品种规格">
          <el-select v-model="ruleForm.specificationId" class="w100p" clearable filterable placeholder="请选择规格"
            @change="getSpecificationName">
            <el-option v-if="s.plantVarietyId == ruleForm.plantVarietyId" v-for="s, index in specificationList"
              :key="index" :label="s.specificationName" :value="s.specificationId"></el-option>
          </el-select>
          <span class="message">{{ validateMsg.specificationId }}</span>
        </el-descriptions-item>
        <el-descriptions-item :span="2" label="重量">
          <el-input type="number" v-model="ruleForm.weight" placeholder="请输入重量" @change="handleChangeWeight">
            <template slot="append">斤</template>
          </el-input>
          <span class="message">{{ validateMsg.weight }}</span>
        </el-descriptions-item>
        <el-descriptions-item :span="2" label="粒数">
          <el-input type="number" v-model="ruleForm.num" placeholder="请输入粒数" @change="handleChangeNum">
            <template slot="append">粒</template>
          </el-input>
          <span class="message">{{ validateMsg.num }}</span>
        </el-descriptions-item>
        <el-descriptions-item :span="2" label="检验人">
          <el-select v-model="ruleForm.staffId" class="w100p" placeholder="请选择操作人" @change="handleChangePerson">
            <el-option v-for="item, index in person" :key="index" :label="item.staffName"
              :value="item.staffId"></el-option>
          </el-select>
          <span class="message">{{ validateMsg.staffId }}</span>
        </el-descriptions-item>
        <el-descriptions-item :span="6" label="检验模板">
          <el-radio-group v-model="ruleForm.templateObj" @change="handleChangeTemplateObj">
            <el-radio v-for="item, index in templateList" :key="index" :label="item">{{ item.templateName
              }}</el-radio>
          </el-radio-group>
        </el-descriptions-item>
        <el-descriptions-item :span="6" label="一票否决">
          <span class="error">注：某个检验范畴内存在一票否决检验科目时，若出现一项"一票否决的检验科目"是不合格（得分为0），则该检验范畴内的检验科目全部不合格。</span>
        </el-descriptions-item>
        <!-- <el-descriptions-item :span="6" label="检验范畴">
        <el-checkbox-group v-model="ruleForm.inspectionScope" @change="handleChangeScope">
          <el-checkbox v-for="item, index in rowList" :key="index" :label="item">{{ item.name
            }}</el-checkbox>
        </el-checkbox-group>
      </el-descriptions-item> -->
      </el-descriptions>
      <div class="th flex" v-show="ruleForm.inspectionScope && ruleForm.inspectionScope.length > 0">
        <div class="f_1 content th_title">范畴</div>
        <div class="f_2 ">
          <div class="flex">
            <div class="content f_2_1 th_title">检验科目</div>
            <div class="content f_2_2 th_title">检验标准</div>
            <div class="content f_2_3 th_title">检验结果</div>
          </div>
        </div>
      </div>
      <div class="content danger" v-show="!Object.keys(ruleForm.templateObj).length">请先选择范畴！
      </div>
      <div v-if="resetRadio" class="tr flex" v-show="item.subject && item.subject.length" v-for="item, index in rowList"
        :key="index">
        <div class="f_1 content">{{ item.name }}</div>
        <div class="f_2">
          <div class="flex" v-for="sub, i in item.subject" :key="i">
            <div class="content f_2_1">{{ sub.checkScopeName }}</div>
            <div class="content f_2_2">
              <span class="error" v-show="sub.oneVoteDownFlag">【{{ sub.oneVoteDownFlag ? '一票否决' : '' }}】</span>
              {{ sub.checkStandard }}【{{ sub.socre }}分】
            </div>
            <div class="content f_2_3">
              <el-input type="number" v-model="sub.receiveSocre" class="w100p" @change="handleReceiveSocre(index, i)"
                clearable placeholder="请输入得分"></el-input>
              <!-- <el-radio-group v-model="sub.checkResult" @change="handleChangeCheckResult">
              <el-radio label="合格">合格</el-radio>
              <el-radio label="不合格">不合格</el-radio>
              <el-radio label="无需检验">无需检验</el-radio>
            </el-radio-group> -->
            </div>
          </div>
        </div>
      </div>
      <div class="totalSocre" v-show="totalSocre > -1">
        <span class="passSocre">合格线：{{ passSocre }}分</span>
        <span>综合得分：
          <span v-show="totalSocre <= 60" :class="totalSocre <= 60 ? 'error' : ''">{{ totalSocre }}分</span>
          <span v-show="totalSocre <= 80 && totalSocre > 60"
            :class="totalSocre <= 80 && totalSocre > 60 ? 'warning' : ''">{{
        totalSocre }}分</span>
          <span v-show="totalSocre <= 100 && totalSocre > 80"
            :class="totalSocre <= 100 && totalSocre > 80 ? 'success' : ''">{{
        totalSocre }}分</span>
        </span>
      </div>
      <el-descriptions :column="6" border>
        <template v-if="userType == 'INSPECTOR'">
          <el-descriptions-item :span="6" label="检验员结论" label-class-name="my-label">
            <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="ruleForm.staffResult">
            </el-input>
          </el-descriptions-item>
          <el-descriptions-item :span="6" label="操作 (提交给技术员审核)" label-class-name="my-label">
            <el-button type="primary" plain @click="submit">提交表单</el-button>
          </el-descriptions-item>
        </template>

        <template v-if="userType == 'TECHNICIAN'">
          <el-descriptions-item :span="6" label="技术员结论">
            <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="ruleForm.technicianResult">
            </el-input>
          </el-descriptions-item>
          <el-descriptions-item :span="1" label="操作 (提交给场长审核)">
            <el-button type="primary" plain @click="submit">提交表单</el-button>
          </el-descriptions-item>

          <el-descriptions-item :span="5" label="结果评定">
            <el-radio-group v-model="ruleForm.technicianStatus">
              <el-radio :label="'合格'">合格准入</el-radio>
              <el-radio :label="'不合格'">不合格拒入</el-radio>
              <el-radio :label="'让步'">让步接收</el-radio>
            </el-radio-group>
          </el-descriptions-item>
          <el-descriptions-item :span="5" label="结果评定">

          </el-descriptions-item>
        </template>

        <template v-if="userType == 'FARMER'">
          <el-descriptions-item :span="6" label="场长结论">
            <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="ruleForm.farmResult">
            </el-input>
          </el-descriptions-item>
          <el-descriptions-item :span="1" label="操作">
            <el-button type="primary" plain @click="submit">确认提交</el-button>
          </el-descriptions-item>
          <el-descriptions-item :span="5" label="结果评定">
            <el-radio-group v-model="ruleForm.farmStatus">
              <el-radio :label="'合格'">合格准入</el-radio>
              <el-radio :label="'不合格'">不合格拒入</el-radio>
              <el-radio :label="'让步'">让步接收</el-radio>
            </el-radio-group>
          </el-descriptions-item>
        </template>
        <!-- // {INSPECTOR: "检验员", TECHNICIAN: "技术员", FARMER: "场长"} -->
      </el-descriptions>
    </div>
  </div>
</template>

<script>
import MainSlot from "@/components/MainSlot";
import inspectionPhase from '@/api/basicInformation/inspectionPhase.js';
import inspectionScope from '@/api/basicInformation/inspectionScope.js';
import inspectionSubject from '@/api/basicInformation/inspectionSubject.js';
import { formatTime } from '@/utils/fmtTime.js';
import inspectionManagement from '@/api/inspectionManagement/inspectionManagement';
import varietyManagement from '@/api/basicInformation/varietyManagement';
import facilityManagement from '@/api/digtalOperation/facilityManagement';
import specificationManagement from '@/api/basicInformation/specificationManagement.js';
import checkScoreConfig from '@/api/basicInformation/checkScoreConfig.js';
import { mapGetters } from 'vuex'

import inspectorAssignment from '@/api/basicInformation/inspectorAssignment.js';
export default {
  components: { MainSlot },
  props: {
    userType: {
      type: String,
      default: () => {
        return ''
      }
    },
    isEdit: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    data: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },

  computed: {
    ...mapGetters([
      'codeList'
    ])
  },
  data() {
    return {
      btnFlag: true,
      resetRadio: true,
      loading: false,
      validateMsg: {},
      radioList: [],
      totalSocre: -1,
      rowList: [
        {
          name: '',
          subject: []
        }
      ],
      ruleForm: {
        checkTime: formatTime(new Date(), 'yyyy-MM-dd HH:mm:ss'),
        inspectionScope: [],
        templateObj: {}
      },
      person: [],
      passSocre: 60,
      facilityList: [],
      varietyList: [],
      templateList: [],
      specificationList: [],
      inspectionScopeList: []
    }
  },
  // computed: {
  //   person() {
  //     return this.$store.state.initData.person || [];
  //   },
  // },
  watch: {
    ruleForm: {
      handler(v) {
        for (let key in v) {
          this.validateForm(v, key)
        }
      },
      deep: true
    }
  },
  mounted() {
    this.btnFlag = this.codeList.indexOf('submit') !== -1;
    this.getRadioList();
    this.getInspectionScope();
    this.initData()
  },
  methods: {
    async initData() {
      let { data: person } = await inspectorAssignment.queryByCondition({ type: 'INSPECTOR' })
      this.person = person
      console.log(person)
      //规格
      let { data: specificationList } = await specificationManagement.queryByCondition({});
      this.specificationList = specificationList;
      //获取品种；
      let { data: varietyList } = await varietyManagement.queryByCondition({})
      this.varietyList = varietyList || [];
      //获取养殖设施；
      let { data: facilityList } = await facilityManagement.getFacilityListByConditionAll({
        breedType: sessionStorage.breedType
      });
      this.facilityList = facilityList || [];
    },
    async handleChangeCheck(e) {
      this.ruleForm.templateObj = {};
      this.rowList = [];
      let checkStageId = e.checkStageId
      let { data: list } = await checkScoreConfig.queryByCondition({ checkStageId });
      this.templateList = list || []
    },
    //选择模板
    async handleChangeTemplateObj(e) {
      this.rowList = [];
      let { data: list } = await checkScoreConfig.findAllByCheckScoreConfigId(e.checkScoreConfigId)
      console.log(list)
      let subject = {};
      // name: item.scopeTypeName,
      // checkScopeTypeId: item.checkScopeTypeId,
      // subject: []
      list.forEach(e => {
        if (!subject[e.checkScopeTypeId]) {
          subject[e.checkScopeTypeId] = []
        }
        subject[e.checkScopeTypeId].push(e)
      })
      for (let key in subject) {
        this.rowList.push({
          name: subject[key][0].scopeTypeName,
          checkScopeTypeId: subject[key][0].checkScopeTypeId,
          subject: subject[key]
        })
      }
      this.passSocre = e.passSocre
      this.totalSocre = 0
      console.log(this.rowList)
    },
    //检验阶段
    async getRadioList() {
      let res = await inspectionPhase.queryByCondition({});
      this.radioList = res.data || []
    },
    //检验范畴
    async getInspectionScope() {
      let res = await inspectionScope.queryByCondition({});
      this.inspectionScopeList = res.data || [];
      this.rowList = this.inspectionScopeList.map(item => {
        return {
          name: item.scopeTypeName,
          checkScopeTypeId: item.checkScopeTypeId,
          subject: []
        }
      })
    },
    handleChangeScope(list) {
      if (!list || list.length == 0) {
        this.rowList = this.rowList.map(item => {
          return { ...item, subject: [] }
        })
      } else {
        let idList = list.map(item => item.checkScopeTypeId)
        list.forEach(item => {
          this.getInspectionSubject(item.checkScopeTypeId, idList)
        })
      }
    },
    handleChangeWeight(e) {
      if (!e || e < 0) {
        this.$message.warning('请输入大于0的数');
        this.ruleForm.weight = Math.abs(e || 0)
      }
    },
    handleChangeNum(e) {
      if (e % 1 !== 0 || e < 0) {
        this.$message.warning('请输入大于0的整数');
        this.ruleForm.num = Math.floor(Math.abs(e || 0))
      }
    },
    //获取科目
    async getInspectionSubject(checkScopeTypeId, idList) {
      let res = await inspectionSubject.queryByCondition({ checkScopeTypeId })
      this.rowList.forEach(item => {
        if (item.checkScopeTypeId == checkScopeTypeId) {
          let subjectList = null
          if (item.subject && item.subject.length > 0) {
            subjectList = JSON.parse(JSON.stringify(item.subject))
          } else {
            subjectList = null
          }
          item.subject = res.data.map((d, index) => {
            return {
              ...d,
              checkResult: subjectList ? subjectList[index].checkResult || '' : ''
            }
          })
        }
        if (!(idList.includes(item.checkScopeTypeId))) {
          item.subject = []
        }
      });
      console.log(this.rowList)
    },
    getPersonName() {
      let result = this.person.find(obj => obj.personNo == this.ruleForm.staffId);
      this.$set(this.ruleForm, 'staffName', result.person.name || "");
    },
    getSpecificationName() {
      let result = this.specificationList.find(obj => obj.specificationId == this.ruleForm.specificationId);
      this.$set(this.ruleForm, 'specificationName', result.specificationName || "");
    },
    getFacilityName() {
      let result = this.facilityList.find(obj => obj.facilityId == this.ruleForm.facilityId);
      this.$set(this.ruleForm, 'facilityName', result.facilityName || "");
    },
    getPlantVarietyName() {
      let result = this.varietyList.find(obj => obj.plantVarietyId == this.ruleForm.plantVarietyId);
      console.log(result, this.facilityList)
      this.$set(this.ruleForm, 'plantVarietyName', result.plantVarietyName || "");
      this.$set(this.ruleForm, 'specificationId', '');
      this.$set(this.ruleForm, 'specificationName', '');
    },
    handleChangePerson(id) {
      let row = this.person.find(item => Number(item.staffId) == id);
      this.$set(this.ruleForm, 'staffName', row.staffName);
    },
    handleCheckResult(e, index, childIndex) {
      let subject = JSON.parse(JSON.stringify(this.rowList[index].subject[childIndex]));
      subject.checkResult = e
      this.rowList[index].subject[childIndex] = subject;
      this.resetRadio = false;
      this.$nextTick(() => {
        this.resetRadio = true;
      })
    },
    handleReceiveSocre() {
      console.log(this.rowList)
      let checkQualityDetailList = []
      this.rowList.forEach(row => {
        row.subject.forEach(item => {
          if (item.receiveSocre > item.socre) {
            this.$message.warning(`该检验科目最高分为${item.socre}分`)
            item.receiveSocre = item.socre;
          } else if (item.receiveSocre < 0) {
            this.$message.warning(`请正确输入分值!`);
            item.receiveSocre = 0;
          }
          if (item.receiveSocre) {
            item.receiveSocre = Number(item.receiveSocre).toFixed(2)
            item.receiveSocre = Number(item.receiveSocre)
          }
        })
        checkQualityDetailList = checkQualityDetailList.concat(row.subject)
      })

      this.totalSocre = this.calculateScore(checkQualityDetailList)
    },
    handleChangeCheckResult() {
      let checkQualityDetailList = []
      this.rowList.forEach(row => {
        checkQualityDetailList = checkQualityDetailList.concat(row.subject)
      })
      this.totalSocre = this.calculateScore(checkQualityDetailList)
    },
    calculateScore(list = []) {
      console.log(list)
      let oneVoteDownItemList = list.filter(e => {
        return typeof e.receiveSocre === "number" && e.receiveSocre == 0 && e.oneVoteDownFlag
      })
      let checkScopeTypeIdList = oneVoteDownItemList.map(e => e.checkScopeTypeId);
      console.log(checkScopeTypeIdList)
      let totalSocreItem = list.filter(e => {
        return !checkScopeTypeIdList.includes(e.checkScopeTypeId)
      })
      return totalSocreItem.reduce((sum, current) => sum + Number(current.receiveSocre || 0), 0);
    },
    submit() {
      if (!this.btnFlag) {
        this.$message.warning('无权限操作')
        return
      }
      let checkQualityDetailList = []
      let checkStageId = this.ruleForm.checkStage ? this.ruleForm.checkStage.checkStageId || '' : ''
      this.rowList.forEach(row => {
        checkQualityDetailList = checkQualityDetailList.concat(row.subject)
      })
      let params = {
        ...this.ruleForm,
        checkStageId: checkStageId,
        checkQualityDetailList: checkQualityDetailList
      };
      let filterItem = checkQualityDetailList.filter(item => {
        return !(item.receiveSocre+'')
      });
      this.validateForm(params)
      if (Object.keys(this.validateMsg).length) {
        return
      }
      if (filterItem.length > 0 || checkQualityDetailList.length == 0) {
        this.$message.warning('完善检验项结果再继续提交！')
        return
      }
      inspectionManagement.add({
        ...params,
        status: 'TECHNICAL_EVALUATION',
        totalSocre: Number(this.calculateScore(params.checkQualityDetailList) || 0),
        passSocre:this.passSocre
      }).then(res => {
        console.log(res)
        if (res.code == 1) {
          this.$message.success('操作成功')
          setTimeout(() => {
            this.isResetData();
          }, 1000)
        } else {
          this.$message.warning('操作失败')
        }
      }).catch(err => {
        console.log(err)
      })
    },
    isResetData() {
      this.$confirm('是否重置当前数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.resetInfo();
        this.$message({
          type: 'success',
          message: '重置成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消重置'
        });
      });
    },
    resetInfo() {
      this.radioList = [];
      this.rowList = [
        {
          name: '',
          subject: []
        }
      ];
      this.ruleForm = {
        inspectionScope: [],
        templateObj: {},
      };
      this.totalSocre = -1;
      this.facilityList = [];
      this.varietyList = [];
      this.specificationList = [];
      this.inspectionScopeList = [];
      this.getRadioList();
      this.getInspectionScope();
      this.initData();
      setTimeout(() => {
        this.validateMsg = {};
      }, 1000);
    },
    validateForm(params, key) {
      params = params || this.ruleForm;
      let validateObj = {
        plantVarietyId: '请选择品种！',
        checkStage: '请选择检验阶段！',
        supplier: '请输入供应商！',
        checkTime: '请选择检验时间！',
        codeNo: '请输入码单号！',
        facilityId: '请选择设施！',
        staffId: '请选择检验员！',
        specificationId: '请选择规格！',
        num: '请输入粒数！',
        weight: '请输入重量！'
      }
      let validate = {}
      if (key) {
        console.log(params[key])
        if (params[key]) {
          delete this.validateMsg[key]
        } else {
          this.validateMsg[key] = validateObj[key] || ''
        }
        console.log(this.validateMsg)
      } else {
        for (let key in validateObj) {
          if (!params[key]) {
            validate[key] = validateObj[key]
          }
        }
        this.validateMsg = validate
      }
    },
  }
};
</script>

<style lang="scss" scoped>
.inspectionSheet {
  width: 100%;
  height: 100%;
  padding: 0 10px;
  overflow-y: auto;

  .mian {
    background-color: #ffffff;
    padding: 20px;
  }
}

.flex {
  display: flex;
  justify-content: flex-start;

  .f_1 {
    width: 10%;
  }

  .f_2 {
    width: 90%;
  }

  .f_2_1 {
    width: 15%;
  }

  .f_2_2 {
    width: 65%;
  }

  .f_2_3 {
    width: 30%;
  }

}

.th {
  .th_title {

    font-weight: bold;
  }
}

.tr {
  color: #505050;
  background-color: #ffffff;
}

.titleLable {
  width: 100%;
  box-sizing: border-box;
  color: #909399;
  background: #fafafa;
}

.content {
  border: 1px solid #EBEEF5;
  box-sizing: border-box;
  text-align: left;
  font-weight: 400;
  font-size: 12px;
  line-height: 1.5;
  padding: 6px 10px;
}

.message {
  display: block;
  color: red;
}

::v-deep .my-label {
  width: 300px !important;
}

.error {
  color: red;
}

.warning {
  color: orange;
}

.success {
  color: rgb(0, 153, 255);
}

.totalSocre {
  text-align: right;
  padding: 20px;
  font-size: 20px;
  font-weight: bold;
}
.passSocre{
  padding-right: 20px;
  color: #999999;
}
</style>